package dr.joketalker.model;

import java.util.LinkedList;
import java.util.List;

import android.os.AsyncTask;
import android.provider.SyncStateContract.Constants;

import dr.joketalker.Constant;
import dr.joketalker.dao.JokeDAO;
import dr.joketalker.dao.json.JSONJoke;
import dr.joketalker.entity.Joke;

public class SearchModel extends MyModel{
	
	protected JokeDAO jokeDao  = new JSONJoke();
	
	protected List<Joke> listJoke = new LinkedList<Joke>();
	
	public static SearchModel st_myModel = null;
	
	protected String category = "All";
	
	protected long cid = 0;
	
	protected boolean isStoredMore = true;
	
	public boolean isStoredMore() {
		return isStoredMore;
	}

	public void setStoredMore(boolean isStoredMore) {
		this.isStoredMore = isStoredMore;
	}

	protected boolean isLoading = false;
	
	public boolean isLoading() {
		return isLoading;
	}

	public void setLoading(boolean isLoading) {
		this.isLoading = isLoading;
	}

	public static SearchModel GetInstance(){
		if(st_myModel == null){
			st_myModel = new SearchModel();
		}
		return st_myModel;
	}
	
	protected SearchModel(){
		clear();
	}
	
	public void clear(){
		 category = "All";
		 listJoke.clear();
		 isStoredMore = true;
	}
	
	public List<Joke> getListJoke() {
		return listJoke;
	}

	public void setListJoke(List<Joke> listJoke) {
		this.listJoke = listJoke;
	}





	
	
	public String getCategory() {
		return category;
	}

	public void setCategory(String category) {
		cid = 0;
		this.category = category;
	}


	public void readAll(){
			
		new ReadTask().execute();
			
	}
	
	protected class ReadTask extends AsyncTask<Void, Void, Void> {


		@Override
		protected Void doInBackground(Void... params) {
			
			List<Joke> newJokes = null;
			
			if(category.equals("All")){
				newJokes = jokeDao.readAll(cid);
			}else{
				newJokes = jokeDao.readAllWhere(JokeDAO.CATEGORY, category, cid);
			}
			if(newJokes.size()>0){
				cid = newJokes.get(newJokes.size()-1).getId();
			}
			
			listJoke.addAll(newJokes);
			
			if(newJokes.size() < Constant.JOKEREADLIMIT){
				isStoredMore = false;
			}
			myDebug.v("add newJokes "+ newJokes.size());
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			
			notifyObs();
			setLoading(false);
		}
		
	}

}
